<?php 

/**
 * 积分兑换商品管理
 * @Author      jiating
 * @DateTime    2018-05-22
 */

namespace app\admin\controller;

use \think\Request;
use app\admin\model\Integralproducts;
use app\admin\model\Producttype;
use app\admin\model\Product;
use app\admin\model\Productspecgroups;
use app\admin\model\Store;
use app\common\model\Order;
use app\admin\model\Wxcomponentconf;
use app\admin\model\Storeproduct;

class Integral extends Base{

    public function __construct() {
        parent::__construct();
        $this->model = new Integralproducts();
    }

    public function index(){
        if(!$this->checkStore()) {
            return $this->fetch('public/alert');
        }
        
        $request = Request::instance();
        $param = $request->param();

        $store = Store::where(['tenantId'=>session('TENANT_ID')])->select();
        $type = Producttype::where(['tenantId'=>session('TENANT_ID')])->select();
        $storeId = empty($param) ? $store[0]['id'] : $param['storeId'];

        $this->assign('store',$store);
        $this->assign('type',$type);
        $this->assign('storeId',$storeId);
        return $this->fetch();
    }

    public function indexApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $storeId = $param['storeId'];
        if(empty($param['search']['value'])) {  //排序展示，默认按排序字段由小到大
            $order = 'sort';
        }else{
            $order = json_decode($param['search']['value'],true);
            if($order['order'] == 'sell') {  //TODO 按热卖数量排序
                $order = 'create_time';
            } else if($order['order'] == 'create_time'){  //按事件降序
                $order = 'create_time DESC';
            }else{  //首页推荐的在先
                $order = $order['order'];
            }
        }

        $where = [
            'storeId' => $storeId,
            'status' => ['neq', '2']
        ];
        $list = $this->model->field('a.id,a.recommendation,b.imgUrl,b.title,b.currentPrice,b.id productId')->alias('a')->join('product b','a.productId=b.id')->where($where)->limit($start,$length)->order($order)->select();
        $count = $this->model->where($where)->count();

        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);
    }

    // 删除积分商品-逻辑删除
    public function groupDel(){
        $request = Request::instance();
        $id = $request->param('id');  //积分ID

        $row = $this->model->where('id',$id)->find();
        $productId = $row['productId'];
        $storeId = $row['storeId'];

        $check = $this->check($storeId,$productId,$code,$message);
        if(!$check) {
            return json(['code'=>$code,'message'=>$message]);
        }

        $upd = $this->model->where('id',$id)->update(['status'=>2]);
        if($upd) {
            return json(['code'=>'1','message'=>'删除成功']);
        }
        return json(['code'=>'2','message'=>'删除失败，请重试']);
    }

    // 设置首页推荐
    public function recommend() {
        $request = Request::instance();
        $id = $request->param('id');  //拼团ID
        $recommendation = $request->param('recommendation');  //是否推荐
        $upd = $this->model->where('id',$id)->update(['recommendation'=>$recommendation]);
        if($upd) {
            return json(['code'=>'1','message'=>'设置成功']);
        }
        return json(['code'=>'2','message'=>'推荐失败，请重试']);
    }

    //保存选中商品到integralproducts表
    public function selectPost() {
        $request = Request::instance();
        $param = $request->param();

        $product = json_decode($param['selectId'],true);
        $product = $product['selectId'];

        if(!is_array($product)) {
            $product = (array)$product;
        }

        $storeproductMdl = new Storeproduct();

        $select = $this->model->field('productId')->where(['storeId'=>$param['store_id'],'status'=>1])->select();
        $sid = [];
        foreach ($select as $v) {   //获得已选商品id
            $sid[] = $v['productId'];
        }
        $add = array_diff($product, $sid);   //获得需要添加的商品id
        $del = array_diff($sid, $product);   //获得需要删除的商品id
        // dump($add);
        // dump($del);die;
        $data = [];
        foreach ($add as $v) {
            $data[] = [
                'id' => get_uniqid_id(), 
                'storeId' => $param['store_id'],
                'productId' => $v,
                'create_time' => time()
            ];
        }
        $this->model->insertAll($data);
        foreach ($del as $d) {
            $this->model->where(['storeId'=>$param['store_id'],'productId'=>$d])->delete();
        }
        return json(['status'=>'1','message'=>'修改成功']);
    }

    public function checkOrder(){
        $request = Request::instance();
        $storeId = $request->param('storeId');  //门店ID
        $product_id = $request->param('product_id');  //商品ID
        $code = '1';
        $message = '可删除';
        $this->check($storeId,$product_id,$code,$message);
        return json(['code'=>$code,'message'=>$message]);
    }

    private function check($storeId,$product_id,&$code,&$message){
        $wxcomponent = Wxcomponentconf::alias('a')->join('wxframeconf b','a.frameId=b.id')->where(['linkType'=>'11','linkId'=>$product_id,'b.storeId'=>$storeId])->find();
        if($wxcomponent) {
            $code = '2';
            $message = '此商品被选为首页展示链接，不可删除';
            return false;
        }

        $find = Order::alias('a')->join('orderproductdetail b','a.id=b.orderId')->where(['b.productId'=>$product_id,'a.storeId'=>$storeId,'a.linkType'=>2])->where('a.status','not in',[4,5,7])->find();
        if($find) {
            $code = '2';
            $message = '此商品有未完成订单，不能删除';
            return false;
        }
        return true;
    }

    public function checkPrice(){
        $request = Request::instance();
        $product_id = $request->param('product_id');  //商品ID
        $product = Product::where('id',$product_id)->find();
        if(empty($product['integralPrice'])) {  //检查是否已设置积分价
            return json(['code'=>'2','message'=>'此商品尚未设置积分兑换值，请到商品管理中设置']);
        }
         return json(['code'=>'1','message'=>'']);
    }

     //取得所有商品数据,客户端分页
    public function productList() {
        $request = Request::instance();
        $param = $request->param();

        $storeId = $param['storeId'];
        $where = [
            'store_id' => $storeId,
            'b.tenantId' => session('TENANT_ID'),
        ];
        if(isset($param['search']['value']) && $param['search']['value']) {  //排序展示，默认按排序字段由小到大
            $filter = json_decode($param['search']['value'],true);
            if($filter['typeId']){
                $where['b.typeId'] = $filter['typeId'];
            }
        }

        $list = Storeproduct::alias('a')->join('product b','a.product_id=b.id')->field('b.imgUrl,b.id, b.title,b.currentPrice,b.specClass,a.created,b.typeId')->where($where)->select();
        $count = Storeproduct::alias('a')->join('product b','a.product_id=b.id')->where($where)->count();

        $res = [
            'status' => '1',
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'test' => $param
        ];
        return json($res);
    }


}